const $siteList = $('.site-list')
const $lastLi = $siteList.find('li.last')

const oldHashMap = localStorage.getItem('oldHashMap')
const oldHashMapObject = JSON.parse(oldHashMap)

// 若是oldHashMap 存在，就取第一个，否则取初始值
const hashMap = oldHashMapObject || [
    {
        logo: "G",
        url: "https://www.google.com",
        logoType: "text",
    },
    {
        logo: "B",
        url: "https://www.bilibili.com",
        logoType: "text",
    },
    {
        logo: "B",
        url: "https://cn.bing.com",
        logoType: "text",
    },
    {
        logo: "X",
        url: "https://xiaozhuanlan.com",
        logoType: "text",
    },
    {
        logo: "S",
        url: "https://biaoyansu.com/29.x",
        logoType: "text",
    },
]


// 去除url 中的https/http/www. 等字符
const simplifyUrl = (url) => {
    return url.replace("https://", "")
        .replace("http://", "")
        .replace("www.", "")
        .replace(/\/.*/, "")
    // 删除/ 开头的内容
}


const render = () => {
    $siteList.find("li:not(.last)").remove()
    hashMap.forEach((node, index) => {
        console.log(index)
        const $li = $(`<li>
            <div class="site">
                <div class="logo">${node.logo[0].toUpperCase()}</div>
                <div class="link">${simplifyUrl(node.url)}</div>
                <div class="close">
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-close"></use>
                    </svg>
                </div> 
            </div>
        </li>`).insertBefore($lastLi)
        $li.on("click", () => {
            window.open(node.url)
        })
        // 上面三行代码，代替<a> 标签

        // 点击关闭标签后，阻止冒泡，避免触发window.open() 
        $li.on("click", ".close", (e) => {
            e.stopPropagation()
            // console.log(hashMap)
            hashMap.splice(index, 1)
            render()
            // 删除标签的功能
        })
    })
    // 使用hashmap 构建html 节点
}

render()

const a = $('add-button')
console.log(a)
$('.add-button').on('click', () => {
    const link = window.prompt("请输入添加的网址：")
    if (link.indexOf('http') !== 0) {
        url = 'https://' + link
        // console.log(url)
    }
    console.log($lastLi)
    hashMap.push({
        logo: simplifyUrl(url)[0].toUpperCase(),
        logoType: "text",
        url: url,
    })
    render()

})


window.onbeforeunload = () => {
    const string = JSON.stringify(hashMap)
    localStorage.setItem('oldHashMap', string)
    // 将对象变成字符串，然后存到LocalStorage 中
}

// document.addEventListener()
$(document).on('keypress', (e) => {
    // const key = e.key
    const { key } = e
    for (let i = 0; i < hashMap.length; i++) {
        if (hashMap[i].logo.toLowerCase() === key) {
            window.open(hashMap[i].url)
        }
    }

})